package br.ujr.pocs.activemq.topic;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnectionFactory;

public class ConsumerTopic implements MessageListener {

	String url = "tcp://localhost:61616";
	String topicName = "TOPIC.FOO";
	
	public void start() {
		
    	Connection connection = null;
    	Session session = null;
    	
		try {
			ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
			connection = connectionFactory.createConnection();
			// In case using a Durable Subscriber, that's mandatory
			connection.setClientID("UALTER JR");
			connection.start();
			
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			Topic topic = session.createTopic(topicName);
			
			// Ordinary Consumer
			//MessageConsumer consumer = session.createConsumer(topic);
			
			// Durable Consumer
			MessageConsumer consumer = session.createDurableSubscriber(topic, "UALTER JR.");
			
			
			/* Receive Synchronous */
			//Message message = consumer.receive();
    		//this.writeMessage(topicName, message);
			
			/* Receive Asynchronous */
			consumer.setMessageListener(this);
			while(true);
			
		} catch (JMSException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if ( session != null ) session.close();
				if ( connection != null ) connection.close();
			} catch (JMSException e) {
				throw new RuntimeException(e);
			}
		}
	
	}
	private void writeMessage(Message message) throws JMSException {
		TextMessage textMessage = (TextMessage) message;
		System.out.printf("Subscription \"%s\" \"%s\" consumida.\n", this.topicName, textMessage.getText());
	}
	
	public static void main(String[] args) {
		ConsumerTopic consumerTopic = new ConsumerTopic();
		consumerTopic.start();
	}

	public void onMessage(Message msg) {
		try {
			this.writeMessage(msg);
		} catch (JMSException e) {
			throw new RuntimeException(e);
		}
	}

}
